package com.lagou.module4hw.hw4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器类
 */
public class Server {

    public static void main(String[] args) {

        //1.创建ServerSocket
        ServerSocket serverSocket = null;
        ObjectInputStream ois = null; //对象输入流
        ObjectOutputStream oos = null;
        try {
            //指定端口8888
            serverSocket = new ServerSocket(8888);

            //2.等待客户端连接
            Socket socket = serverSocket.accept();

            //3.接受客户端信息
            InputStream inputStream = socket.getInputStream();
            ois = new ObjectInputStream(inputStream);

            //3.1从输入流中读取对象的信息
            UserMessage userMessage = (UserMessage) ois.readObject();
            System.out.println("客户端传送的信息是: " + userMessage);

            //3.2获取用户信息
            User user = userMessage.getUser();
            String name = user.getName();
            String password = user.getPassword();

            //3.3检查用户信息，并回写check信息
            String check = checkMessage(name,password);
            userMessage.setType(check);


            //4.服务器校验信息完成，把用户信息对象传回客户端
            OutputStream outputStream = socket.getOutputStream();
            oos = new ObjectOutputStream(outputStream);
            oos.writeObject(userMessage);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            try {
                if ( oos != null )oos.close();
                if ( ois != null )ois.close();
                if ( serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 检查用户信息是否为admin password
     * @param name 用户名
     * @param password 密码
     * @return success - 是    fail - 否
     */
    private static String checkMessage(String name, String password) {
        if("admin".equals(name) && "123456".equals(password)){
            return "success";
        }
        return "fail";
    }
}
